package com.wg.wuge.tulin.jmm;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockTest {

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private Map<String, Integer> map = new HashMap<>();

    private Integer getValue(String key) {
        return map.get(key);

    }

    private void putMap(String key, Integer value) {
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
        try{
            writeLock.lock();
            map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }


    public static void main(String[] args) {

        CountDownLatch downLatch = new CountDownLatch(3);
        LockTest lockTest = new LockTest();
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 3; i++) {
            int finalI = i;
            executorService.execute(() ->{
                lockTest.putMap(String.valueOf(finalI) , finalI);
                downLatch.countDown();
            });
        }

        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("=====" + lockTest.getValue("1")+ lockTest.getValue("2")+ lockTest.getValue("0"));
        executorService.shutdown();
    }


}
